using System;
using System.Collections.Generic;
using System.Text;

using Weazel.Microblaze.Simulator.Engine;

namespace Weazel.Microblaze.Simulator.Components.Microblaze.Instructions
{
    /// <summary>
    /// Store Halfword Immediate
    /// </summary>
    public class Shi : MemoryAccessInstruction
    {
        public override int CycleCount
        {
            get { return 1; }
        }

        public Shi()
            : base("shi")
        {
        }

        /// <summary>
        /// Stores the contents of the least significant halfword of register rD, 
        /// into the halfword aligned memory location that results from adding 
        /// the contents of register rA and the value IMM, sign-extended to 32 
        /// bits.
        /// </summary>    
        public override void Execute(MicroblazeComponent MicroblazeComponent)
        {
            uint address =
                MicroblazeComponent.ReadRegister(SourceRegisterA) +
                GetImmediateValue(MicroblazeComponent);

            // mask bit 31 
            address &= 0xFFFFFFFE;

            uint memory = MicroblazeComponent.ReadRegister(DestinationRegister);

            WriteHalfWordTransaction transaction = new WriteHalfWordTransaction(MicroblazeComponent, address, memory);
            MicroblazeComponent.BeginDataTransaction(transaction);

            while (transaction.Status != Transaction.TransactionStatus.Complete)
                MicroblazeComponent.WaitOneCycle();
        }

        public override string ToString()
        {
            return string.Format("shi r{0}, r{1}, {2}",
              DestinationRegister,
              SourceRegisterA,
              ImmediateValue
            );
        }
    }
}
